package site.wanjiahao.session.impl;

import io.netty.channel.Channel;
import site.wanjiahao.session.Session;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用户和channel互相绑定的通道
 */
public class MemorySessionImpl implements Session {

    private static final Map<String, Channel> channelMapping = new ConcurrentHashMap<>();

    private static final Map<Channel, String> usernameMapping = new ConcurrentHashMap<>();

    private static final Map<Channel, Map<Object, Object>> attributes = new ConcurrentHashMap<>();

    @Override
    public synchronized void bind(String username, Channel channel) {
        channelMapping.put(username, channel);
        usernameMapping.put(channel, username);
    }

    @Override
    public synchronized void unbind(Channel channel) {
        String username = usernameMapping.remove(channel);
        if (username != null) {
            System.out.println("移除用户: " + username);
            Channel res = channelMapping.remove(username);
            System.out.println("移除通道: " + username);
            attributes.remove(res);
        }
    }

    @Override
    public synchronized void setAttribute(Channel channel, Object key, Object value) {
        Map<Object, Object> map = attributes.computeIfAbsent(channel, k -> new HashMap<>());
        map.put(key, value);
        attributes.put(channel, map);
    }

    @Override
    public synchronized Object getAttribute(Channel channel, Object key) {
        Map<Object, Object> map = attributes.get(channel);
        if (map != null) {
            return map.get(key);
        }
        return null;
    }

    @Override
    public Channel getChannel(String username) {
        return channelMapping.get(username);
    }

    @Override
    public String getUsername(Channel channel) {
        return usernameMapping.get(channel);
    }
}
